package cc.dullsky.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

public class NetEaseUtil {
	/**
	 * 网易云音乐API-get请求
	 * 
	 * @param url
	 *            请求的地址
	 * @return String 返回的字符串
	 */
	public static JSONObject doGetStr(String url) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		String result = null;
		try {
			httpGet.addHeader("Cookie", "appver=1.5.0.75771");
			httpGet.addHeader("Referer", "http://music.163.com/");
			HttpResponse response = httpClient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity, "UTF-8");
			}
			httpClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONObject.parseObject(result);
	}

	/**
	 * 网易云音乐API-post请求
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            传入参数
	 * @return String 返回的字符串
	 */
	public static JSONObject doPostStr(String url, Map<String, String> params) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		String result = null;
		try {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			for (Map.Entry<String, String> entry : params.entrySet()) {
				nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
			httpPost.addHeader("Cookie", "appver=1.5.0.75771");
			httpPost.addHeader("Referer", "http://music.163.com/");
			HttpResponse response = httpClient.execute(httpPost);
			result = EntityUtils.toString(response.getEntity(), "UTF-8");
			httpClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONObject.parseObject(result);
	}
}
